﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PilotProject;
using PilotMVC.Models;

namespace PilotMVC.Controllers
{
    [Authorize(Roles = "Candidate")]
    public class QuizController : Controller
    {
        //
        // GET: /Quiz/
    

        public ActionResult Load(Guid id)
        {

            var testView = new TestView();
            using (var context = new PilotEntities1())
            {
                var token = context.TestTokens.Where(a => a.Id.Equals(id)).Single();
                testView.Test = token.GenerateTest();
                context.SaveChanges();
                Session.Add("CurrentQuestion", token.Test.TestQuestions.OrderBy(q=>q.QuestionOrder).First().QuestionOrder);


                if (token.TimeAllowedInMinutes > 0)
                {
                    var quizQuestion = new QuizQuestionView();
                    TimerView timer = new TimerView();
                    timer.Minutes = token.TimeAllowedInMinutes;
                    timer.Start();

                    quizQuestion.TimeLeft = timer.UpdatedTime;
                }

            }
            return RedirectToAction("Next", new { testView.Test.Id });
        }

        public ActionResult Next(Guid id)
        {
            var quizQuestion = new QuizQuestionView();
            quizQuestion.Date = DateTime.Now;

            using (var context = new PilotEntities1())
            {
                var test = context.Tests.Where(a => a.Id.Equals(id)).Single();
                int lastOrderedQuestion = (int)Session["CurrentQuestion"];
                var question = test.TestQuestions.Where(q => q.QuestionOrder == lastOrderedQuestion).FirstOrDefault();
                
                if (question != null)
                {
                    quizQuestion.TestQuestion = question;
                    quizQuestion.Options = question.Options.ToList();

                    var previousTestQuestion = test.TestQuestions.Where(a => a.QuestionOrder == (int)Session["CurrentQuestion"]).SingleOrDefault();
                    quizQuestion.selectedPreviousAnswer = test.Answers.Where(b => b.Option.QuestionId.Equals(previousTestQuestion.QuestionId)).SingleOrDefault();

                   
                    quizQuestion.numberOfQuestion = test.TestToken.NoOfQuestions;
                    quizQuestion.currentQuestionNumber = lastOrderedQuestion;
                    return View(quizQuestion);
                }
                else
                {
                    test.CompleteTest();
                    context.SaveChanges();
                    return RedirectToAction("CompleteTest", new { testID= test.Id }); 
                } 
            }     
        }


        public ActionResult CompleteTest(Guid id)
        {
            var testResult = new TestResultView();
            testResult.Date = DateTime.Now.Date;
            using (var context = new PilotEntities1())
            {
                var test = context.Tests.Where(a => a.Id.Equals(id)).Single();
                var numberOfQuestion = test.TestToken.NoOfQuestions;

                foreach (var answer in test.Answers)
                {
                    if (answer.Option.IsCorrect == true)
                    {
                        testResult.correctAnswer++;
                    }
                    else
                    {
                        testResult.incorrectAnswer++;
                    }
                }

                if (testResult.correctAnswer + testResult.incorrectAnswer != numberOfQuestion)
                {
                    testResult.incorrectAnswer = numberOfQuestion - testResult.correctAnswer;
                }

                testResult.score = (testResult.correctAnswer * 100) / numberOfQuestion;
                testResult.passMark = test.TestToken.PassmarkAsPercentage;

                test.RecordResult = testResult.score;
                test.CompleteTest();
                context.SaveChanges();
            }

            return View(testResult);
        }


        [HttpPost]
        public ActionResult SaveAnswer(string submitAnswer, QuizQuestionView model)
        {
            using (var context = new PilotEntities1())
            {
                var selectedTest = context.Tests.Where(item => item.Id.Equals(model.TestQuestion.TestId)).Single();
                //var selan = model.SelectedAnswe

                if (model.SelectedAnswer != null)
                {
                    var selectedOption = context.Options.Where(item => item.Id.Equals(model.SelectedAnswer.OptionId)).SingleOrDefault();

                    var previousTestQuestion = selectedTest.TestQuestions.Where(a => a.QuestionOrder == (int)Session["CurrentQuestion"]).SingleOrDefault();
                    var previousAnswer = selectedTest.Answers.Where(b => b.Option.QuestionId.Equals(previousTestQuestion.QuestionId)).SingleOrDefault();

                    if (previousAnswer != null && selectedOption != null)
                    {
                        context.Answers.DeleteObject(previousAnswer);
                        context.SaveChanges();
                        var currentAnswer = new Answer(selectedTest, selectedOption);
                        context.AddToAnswers(currentAnswer);
                        context.SaveChanges();
                    }

                    else if (previousAnswer == null && selectedOption != null)
                    {
                        var selectedAnswer = new Answer(selectedTest, selectedOption);
                        context.AddToAnswers(selectedAnswer);
                        context.SaveChanges();
                    }
                }


                if (submitAnswer == "Next")
                {
                    Session["CurrentQuestion"] = ((int)Session["CurrentQuestion"]) + 1;
                    return RedirectToAction("Next", new { id = selectedTest.Id });
                }
                else if (submitAnswer == "Submit")
                {
                    return RedirectToAction("CompleteTest", new { id = selectedTest.Id });
                }
                else
                {
                    Session["CurrentQuestion"] = ((int)Session["CurrentQuestion"]) - 1;
                    return RedirectToAction("Next", new { id = selectedTest.Id });
                }
            }
        }
        
    }
}
